//
//  DLMachineNormalTC.m
//  delongzhitou
//
//  Created by Mr.Wang on 2018/11/26.
//  Copyright © 2018 delongzhitou. All rights reserved.
//

#import "DLMachineNormalTC.h"
#import "DLMachineModel.h"


@interface DLMachineNormalTC()

@property (nonatomic, strong) UIView *contentBgView;

@property (nonatomic, strong) UILabel *contentLabel;

@property (nonatomic, strong) CALayer *layerrr;


@end


@implementation DLMachineNormalTC


- (instancetype) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        kuserManager.currentSpeakingText = @"";
        
        [self layoutsubControls];
        self.backgroundColor = kDLMachineTableAndCellBgColor;
//        self.backgroundColor = kColorRGB(240, 240, 240);
//        self.backgroundColor = kColorRandom;
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playVideoNotification) name:@"playVideoNotification" object:nil];
    }
    return self;
}
- (void) playVideoNotification {
    NSLog(@"gView.backgroundColo");
    [self stopXunFeiSpeaker];
}
- (void) layoutsubControls {
    
    UIView *contentBgView = [UIView new];
    contentBgView.frame = CGRectMake(0, 0, 0, 0);
    contentBgView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:contentBgView];
    self.contentBgView = contentBgView;
    
    
    UILabel *contentLabel = [UILabel new];
    contentLabel.frame = CGRectMake(kMachineNormalTCLabelEdgeInsetLeftRight, 0, 0, 0);
    contentLabel.font = kMachineNormalTCTextFontSelf;
    contentLabel.textColor = [UIColor whiteColor];
    contentLabel.textAlignment = NSTextAlignmentLeft;
    contentLabel.numberOfLines = 0;
    contentLabel.lineBreakMode = NSLineBreakByCharWrapping;
    contentLabel.userInteractionEnabled = YES;
    contentLabel.backgroundColor = [UIColor clearColor];
    [contentBgView addSubview:contentLabel];
    self.contentLabel = contentLabel;
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentLabelTap)];
    [contentLabel addGestureRecognizer:tapGes];
    
    
    CALayer *layerrr = [[CALayer alloc] init];
    layerrr.backgroundColor = kColorRandom.CGColor;
    layerrr.frame = CGRectMake(10, 10, 100, 40);
//    [self.contentView.layer addSublayer:layerrr];
//    self.layerrr = layerrr;
    
    TTSConfig *instance = [TTSConfig sharedInstance];
    if (instance == nil) {
        return;
    }
    
    //TTS singleton
    if (_iFlySpeechSynthesizer == nil) {
        _iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    }
    
    _iFlySpeechSynthesizer.delegate = self;
    
    //set the resource path, only for offline TTS
    NSString *resPath = [[NSBundle mainBundle] resourcePath];
    NSString *newResPath = [[NSString alloc] initWithFormat:@"%@/aisound/common.jet;%@/aisound/xiaoyan.jet",resPath,resPath];
    [[IFlySpeechUtility getUtility] setParameter:@"tts" forKey:[IFlyResourceUtil ENGINE_START]];
    [_iFlySpeechSynthesizer setParameter:newResPath forKey:@"tts_res_path"];
    
    //set speed,range from 1 to 100.
    [_iFlySpeechSynthesizer setParameter:instance.speed forKey:[IFlySpeechConstant SPEED]];
    
    //set volume,range from 1 to 100.
    [_iFlySpeechSynthesizer setParameter:instance.volume forKey:[IFlySpeechConstant VOLUME]];
    
    //set pitch,range from 1 to 100.
    [_iFlySpeechSynthesizer setParameter:instance.pitch forKey:[IFlySpeechConstant PITCH]];
    
    //set sample rate
    [_iFlySpeechSynthesizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
    
    //set TTS speaker
    [_iFlySpeechSynthesizer setParameter:instance.vcnName forKey:[IFlySpeechConstant VOICE_NAME]];
    
    //set text encoding mode
    [_iFlySpeechSynthesizer setParameter:@"unicode" forKey:[IFlySpeechConstant TEXT_ENCODING]];
    
    //set engine type
    [_iFlySpeechSynthesizer setParameter:instance.engineType forKey:[IFlySpeechConstant ENGINE_TYPE]];
    
    NSDictionary* languageDic=@{@"catherine":@"text_english",//English
                                @"xiaoyan":@"text_vietnam",//Vietnamese
                                @"Abha":@"text_hindi",//Hindi
                                @"Gabriela":@"text_spanish",//Spanish
                                @"Allabent":@"text_russian",//Russian
                                @"Mariane":@"text_french"};//French
    
    NSString* textNameKey=[languageDic valueForKey:instance.vcnName];
    NSString* textSample=nil;
    
    if(textNameKey && [textNameKey length]>0){
        textSample=NSLocalizedStringFromTable(textNameKey, @"tts/tts", nil);
    }else{
        textSample=NSLocalizedStringFromTable(@"text_chinese", @"tts/tts", nil);
    }
}
//结束回调
- (void)onCompleted:(IFlySpeechError *)error {
    NSLog(@"结束回调");
}
// 开始合成回调
- (void) onSpeakBegin {
    NSLog(@"开始合成回调");
}
- (void) contentLabelTap {
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playAudioNotification" object:nil];
    
    
    NSLog(@"%@-%@", kuserManager.currentSpeakingText, self.normalModel.content);
    
    NSLog(@"播放啊，肥仔~");
    if (_audioPlayer != nil && _audioPlayer.isPlaying == YES) {
        [_audioPlayer stop];
    }
    
    if ([self.normalModel.content isEqualToString:kuserManager.currentSpeakingText] && self.iFlySpeechSynthesizer.isSpeaking == YES) {
        NSLog(@"当前播放的和现在点击的是同一条消息，停止播放");
        NSLog(@"前--------%d", self.iFlySpeechSynthesizer.isSpeaking);
        
        [self stopXunFeiSpeaker];
        return;
    } else {
        NSLog(@"当前播放的和现在点击的不是同一条消息，停止播放当前播放的，播放刚才点击的");
        kuserManager.currentSpeakingText = self.normalModel.content;
    }
    
    _synType = NomalType;
    
    self.hasError = NO;
    [NSThread sleepForTimeInterval:0.05];
    self.isCanceled = NO;
    
    _iFlySpeechSynthesizer.delegate = self;
    
    NSString* str= self.contentLabel.text;
    NSLog(@"播放的语音对应的文字是：%@", str);
    [_iFlySpeechSynthesizer startSpeaking:str];
    if (_iFlySpeechSynthesizer.isSpeaking) {
        _state = Playing;
    }
}
- (void) stopXunFeiSpeaker {
    [self.iFlySpeechSynthesizer stopSpeaking];
    [_audioPlayer stop];
    kuserManager.currentSpeakingText = @"";
    _state = NotStart;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"后--------%d", self.iFlySpeechSynthesizer.isSpeaking);
    });
}
- (void) setNormalModel:(DLMachineModel *)normalModel {
    _normalModel = normalModel;
    
    NSString *originContent = [NSString stringWithFormat:@"%@ ", normalModel.content];
    
    NSString *content = @"";
    if ([originContent hasPrefix:@"\n"]) {
        content = [originContent substringFromIndex:1];
    } else {
        content = originContent;
    }
    
    NSString *newContent = @"";
    
    NSLog(@"文本消息是：%@", content);
    
    if (normalModel.isServerMsgCanTransformToVoice == YES) {
        NSLog(@"自动转语音播放");
        self.contentLabel.userInteractionEnabled = YES;
        
        //富文本
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:content];
        
        NSTextAttachment *attchment2 = [[NSTextAttachment alloc]init];
        attchment2.bounds = CGRectMake(0, -6, 22, 22);//设置frame
        attchment2.image = [UIImage imageNamed:@"machine_natification"];//设置图片
        
        NSAttributedString *string2 = [NSAttributedString attributedStringWithAttachment:(NSTextAttachment *)(attchment2)];
        [attributedString appendAttributedString:string2];
        
        self.contentLabel.attributedText = attributedString;
        
        newContent = [NSString stringWithFormat:@"%@一n", content];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            if (kuserManager.isLastMsgVoice == YES) {
                [self contentLabelTap];
            }
        });
        
    } else {
        NSLog(@"不允许自动转语音播放");
        self.contentLabel.userInteractionEnabled = NO;
        
        //正常显示
        self.contentLabel.text = content;
        newContent = self.contentLabel.text;
    }
    
    NSString *contentWithoutHuanHang1 = [newContent stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    NSString *contentWithoutHuanHang = [contentWithoutHuanHang1 stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    CGFloat newWidth = 0.0;
    CGFloat newHeight = 0.0;
    
    
    if (normalModel.msgFrom == SocketMsgFrom_self) {
        newWidth = [contentWithoutHuanHang getValue4WidWithHeight:kMachineNormalTCLabelHeight andFont:kMachineNormalTCTextFontSelf];
        newHeight = [newContent getValue4HeightWithWid:kMachineNormalTCLabelMaxWidth andFont:kMachineNormalTCTextFontSelf];
    } else {
        newWidth = [contentWithoutHuanHang getValue4WidWithHeight:kMachineNormalTCLabelHeight andFont:kMachineNormalTCTextFontOther];
        newHeight = [newContent getValue4HeightWithWid:kMachineNormalTCLabelMaxWidth andFont:kMachineNormalTCTextFontOther];
    }
    
    if (newWidth <= kMachineNormalTCLabelMaxWidth ) {
        
        if (newWidth < 25) {
            newWidth = 25;
        }
        
        if (newHeight <= kMachineNormalTCLabelHeight) {
            newHeight = kMachineNormalTCLabelHeight;
            
            //
            [self.contentBgView resetWidth:newWidth + kMachineNormalTCLabelEdgeInsetLeftRight *2 + 15];
            [self.contentBgView resetHeight:kMachineNormalTCLabelHeight];
            
            [self.contentLabel resetWidth:newWidth + 15];
            [self.contentLabel resetHeight:kMachineNormalTCLabelHeight];
        } else {
            
            //
            [self.contentBgView resetWidth:newWidth + kMachineNormalTCLabelEdgeInsetLeftRight *2];
            [self.contentBgView resetHeight:newHeight + kMachineNormalTCLabelEdgeInsetLeftRight *2];
            
            [self.contentLabel resetWidth:newWidth];
            [self.contentLabel resetHeight:self.contentBgView.height];
        }
        
    } else {
        
        //
        [self.contentBgView resetWidth:kMachineNormalTCLabelMaxWidth + kMachineNormalTCLabelEdgeInsetLeftRight * 2];
        [self.contentBgView resetHeight:newHeight + kMachineNormalTCLabelEdgeInsetLeftRight * 2];
        
        [self.contentLabel resetWidth:self.contentBgView.width - kMachineNormalTCLabelEdgeInsetLeftRight * 2];
        [self.contentLabel resetHeight:self.contentBgView.height];

    }
    
    [self.contentBgView resetY:kMachineNormalTCLabelEdgeInsetTopBottom];
    
    
    UIBezierPath *maskPath;
    if (normalModel.msgFrom == SocketMsgFrom_self) {
        
        [self.contentBgView resetX:kScreenWidth - kMachineNormalTCTextBgViewLeftMargin - self.contentBgView.width];
        
        self.contentLabel.font = kMachineNormalTCTextFontSelf;
        self.contentLabel.textColor = [UIColor whiteColor];
        self.contentBgView.backgroundColor = kDLBtnNormalBgColor;
        
        self.layerrr.frame = self.contentBgView.frame;
        
        maskPath = [UIBezierPath bezierPathWithRoundedRect:self.contentBgView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(17, 17)];
    } else {
        
        [self.contentBgView resetX:kMachineNormalTCTextBgViewLeftMargin];
        
        if (normalModel.isDefaultMachineMsg == YES) {
            
            [self.contentBgView resetWidth:kMachineNormalTCLabelMaxWidth];
            [self.contentBgView resetHeight:[normalModel.content getValue4HeightWithWid:kMachineNormalTCLabelMaxWidth andFont:kBoldFont(18)]];
            
            [self.contentLabel resetWidth:self.contentBgView.width - kMachineNormalTCLabelEdgeInsetLeftRight * 2];
            [self.contentLabel resetHeight:[normalModel.content getValue4HeightWithWid:kMachineNormalTCLabelMaxWidth andFont:kBoldFont(18)]];
            
            self.contentBgView.backgroundColor = [UIColor clearColor];
            
            self.contentLabel.font = kBoldFont(18);
            self.contentLabel.textColor = kDLNormalBlackColor;
        } else {
            
            self.contentBgView.backgroundColor = [UIColor whiteColor];
            
            self.contentLabel.font = kMachineNormalTCTextFontOther;
            self.contentLabel.textColor = kDLNormalBlackColor;
            
            if (normalModel.isKLineMsg == YES) {
                
                self.contentLabel.text = content;
                NSMutableAttributedString *attributedString1 = [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
                NSRange range1;
                NSRange range2;
                
                NSString * upOrDownNumStirng = [NSString stringWithFormat:@"%.2f", fabs(normalModel.upOrDownNum.doubleValue)];
                
                NSString *upOrDownPercentString = [NSString stringWithFormat:@"%.2f", fabs(normalModel.upOrDownPercent.doubleValue)];
                
                range1 = NSMakeRange(14 + normalModel.currentClose.length, upOrDownPercentString.length + 1);
                
                range2 = NSMakeRange(14 + normalModel.currentClose.length + upOrDownPercentString.length + 4, upOrDownNumStirng.length);
                
                
                if (normalModel.isGoUp == YES) {
                    
                    [attributedString1 addAttribute:NSForegroundColorAttributeName
                                              value:kColorRGB(255, 90, 62)
                                              range:range1];
                    [attributedString1 addAttribute:NSForegroundColorAttributeName
                                              value:kColorRGB(255, 90, 62)
                                              range:range2];
                } else {
                    [attributedString1 addAttribute:NSForegroundColorAttributeName
                                              value:kColorRGB(126, 211, 33)
                                              range:range1];
                    [attributedString1 addAttribute:NSForegroundColorAttributeName
                                              value:kColorRGB(126, 211, 33)
                                              range:range2];
                }
                
                self.contentLabel.attributedText = attributedString1;
            } else {
                
                self.contentBgView.backgroundColor = [UIColor whiteColor];
            }
        }
        
        maskPath = [UIBezierPath bezierPathWithRoundedRect:self.contentBgView.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(17, 17)];
        
    }
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = maskPath.bounds;
    maskLayer.path = maskPath.CGPath;
    self.contentBgView.layer.mask  = maskLayer;
    
//    self.contentBgView.backgroundColor = [UIColor redColor];
//    self.contentLabel.backgroundColor = [UIColor greenColor];
    
    if (self.contentBgView.height <= kMachineNormalTCLabelHeight) {
        //一行，字体居中
        if (normalModel.isDefaultMachineMsg == NO) {
            self.contentLabel.textAlignment = NSTextAlignmentCenter;
        }
    } else {
        //多行，字体居左
        self.contentLabel.textAlignment = NSTextAlignmentLeft;
    }
}


- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}


@end
